package com.wh.codedemon.trace.filter;

import com.wh.codedemon.trace.utils.TraceIdUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * TODO
 *
 * @auther whoo7
 * @date 2023/12/31 22:51
 */
@Slf4j
public class TraceFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("init trace filter----------------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String traceId = request.getHeader(TraceIdUtil.TRACE_ID_KEY);
            if (StringUtils.hasText(traceId)) {
                TraceIdUtil.generateTraceId(traceId);
            } else {
                TraceIdUtil.generateTraceId();
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error("获取TraceId异常:", e);
        } finally {
            // 相当于ThreadLocal,防止内存泄漏
            TraceIdUtil.removeTraceId();
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("destroy trace filter------------------");
    }
}
